package com.lt.view;

import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.text.InputFilter;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.DimenRes;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.lt.app.ResHelper;
import com.lt.base.BaseApplication;
import com.lt.common.BitmapDecoder;

public class ViewHelper {
    private static ViewHelper instance;

    public static ViewHelper getInstance() {
        if (instance == null) {
            synchronized (ViewHelper.class) {
                instance = new ViewHelper();
            }
        }
        return instance;
    }

    private ViewHelper() {
    }

    /**
     * 获取焦点
     */
    public void requestFocus(View v) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        v.requestFocus();
    }

    /**
     * @return 判断点击的位置是不是在指定的view上
     */
    public boolean inRangeOfView(View view, MotionEvent ev) {
        if (view == null) return false;
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        return !(ev.getX() < x || ev.getX() > (x + view.getWidth()) || ev.getY() < y || ev.getY() > (y + view.getHeight()));
    }


    /**
     * 修改整个布局的字体
     *
     * @param root 根布局
     * @param tf   字体
     */
    public void replaceFont(View root, Typeface tf) {
        if (root == null || tf == null) {
            return;
        }
        if (root instanceof TextView) {
            TextView textView = (TextView) root;
            int style = Typeface.NORMAL;
            if (textView.getTypeface() != null) {
                style = textView.getTypeface().getStyle();
            }
            textView.setTypeface(tf, style);
        } else if (root instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) root;
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                replaceFont(viewGroup.getChildAt(i), tf);
            }
        }
    }

    /**
     * 不改变控件位置，修改控件大小
     */
    public void setViewSize(View view, int width, int height) {
        if (view.getLayoutParams() != null) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            if (width != 0) {
                layoutParams.width = width;
            }
            if (height != 0) {
                layoutParams.height = height;
            }
            view.setLayoutParams(layoutParams);
        }
    }

    public void setViewHeight(View view, int height) {
        setViewSize(view, 0, height);
    }


    public int getViewHeight(View view) {
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return view.getMeasuredHeight();
    }

    /**
     * 将TextView的字体设置为粗体
     */
    public void setBold(TextView tv) {
        tv.getPaint().setFakeBoldText(true);
    }

    /**
     * 给textview的字体加下划线
     */
    public static void setTextViewUnderLine(TextView tv) {
        tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tv.getPaint().setAntiAlias(true);
    }

    /**
     * 禁止EditText输入空格
     */
    public void setEditTextInhibitInputSpace(EditText editText) {
        InputFilter filter = (source, start, end, dest, dstart, dend) -> {
            if (source.equals(" ")) return "";
            else return null;
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    public void setMargins(View v, int l, int t, int r, int b) {
        try {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setMargins(View v, Class<?> cls, int l, int t, int r, int b) {
        try {
            if (cls == ViewGroup.MarginLayoutParams.class) {
                ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
                p.setMargins(l, t, r, b);
            } else if (cls == ConstraintLayout.LayoutParams.class) {
                ConstraintLayout.MarginLayoutParams p = (ConstraintLayout.MarginLayoutParams) v.getLayoutParams();
                p.setMargins(l, t, r, b);
            }
            v.requestLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给view设置新背景，并回收旧的背景图片<br>
     * <font color=red>注意：需要确定以前的背景不被使用</font>
     */
    @SuppressWarnings("deprecation")
    public void setAndRecycleBackground(View v, int resID) {
        // 获得ImageView当前显示的图片
        Bitmap bitmap1 = null;
        if (v.getBackground() != null) {
            try {
                //若是可转成bitmap的背景，手动回收
                bitmap1 = ((BitmapDrawable) v.getBackground()).getBitmap();
            } catch (ClassCastException e) {
                //若无法转成bitmap，则解除引用，确保能被系统GC回收
                v.getBackground().setCallback(null);
            }
        }
        // 根据原始位图和Matrix创建新的图片
        v.setBackgroundResource(resID);
        // bitmap1确认即将不再使用，强制回收，这也是我们经常忽略的地方
        if (bitmap1 != null && !bitmap1.isRecycled()) {
            bitmap1.recycle();
        }
    }

    /**
     * 给view设置新背景，并回收旧的背景图片<br>
     * <font color=red>注意：需要确定以前的背景不被使用</font>
     */
    @SuppressWarnings("deprecation")
    public void setAndRecycleBackground(View v, BitmapDrawable imageDrawable) {
        // 获得ImageView当前显示的图片
        Bitmap bitmap1 = null;
        if (v.getBackground() != null) {
            try {
                //若是可转成bitmap的背景，手动回收
                bitmap1 = ((BitmapDrawable) v.getBackground()).getBitmap();
            } catch (ClassCastException e) {
                //若无法转成bitmap，则解除引用，确保能被系统GC回收
                v.getBackground().setCallback(null);
            }
        }
        // 根据原始位图和Matrix创建新的图片
//        v.setBackgroundDrawable(imageDrawable);
        if (Build.VERSION.SDK_INT > 15) {
            v.setBackground(imageDrawable);
        } else {
            v.setBackgroundDrawable(imageDrawable);
        }
        // bitmap1确认即将不再使用，强制回收，这也是我们经常忽略的地方
        if (bitmap1 != null && !bitmap1.isRecycled()) {
            bitmap1.recycle();
        }
    }

    public void setAndRecycleBackground(View v, int resId, int width, int height) {
        Bitmap bitmap = BitmapDecoder.getInstance().decodeSampledBitmapFromResource(BaseApplication.getContext().getResources(), resId, width, height);
        if (bitmap == null) {
            return;
        }
        BitmapDrawable drawable = new BitmapDrawable(BaseApplication.getContext().getResources(), bitmap);
        setAndRecycleBackground(v, drawable);
    }

    public void setTextView(TextView tv, Object text) {
        if (tv == null || text == null) {
            return;
        }
        if (text instanceof Integer) {
            tv.setText(ResHelper.getString((int) text));
        } else {
            tv.setText((CharSequence) text);
        }
    }

    public void setTextSize(TextView tv, @DimenRes int resId) {
        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, ResHelper.getInstance().getDimensPx(resId));
    }

    public void setEditLength(EditText edit, int length) {
        //手动设置maxLength为20
        InputFilter[] filters = {new InputFilter.LengthFilter(length)};
        edit.setFilters(filters);
    }

    /**
     * @param radius 角度
     * @param color  背景颜色
     * @return 返回带圆角的Drawable
     */
    public GradientDrawable getRadiusColorDrawable(int radius, int color) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        drawable.setCornerRadius(radius);
        drawable.setColor(color);
        return drawable;
    }
}
